package sisi.unitmeasure;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.CreateEvent;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zk.ui.sys.ComponentsCtrl;
import org.zkoss.zk.ui.util.ConventionWires;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Toolbarbutton;
import org.zkoss.zul.Window;

import sisi.General;
import sisi.ListaStandardWindow;


/**
 * UnitmeasureWindow.java - Controller class for <i>Unit measure terms window</i>. 
 * @author Pedro Gonzalez pedro@sisisoftware.it
 * @author Claudio Pelosi claudio@sisisoftware.it
 * @author SISI Software S.n.c. - www.sisisoftware.it
 * @version 1.0, 19/11/2013
 * 
 */

@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
public class UnitmeasureWindow extends Window implements
		org.zkoss.zk.ui.ext.AfterCompose, ListaStandardWindow {
	
	// listbox boxUnitmeasure
	private Window windowUnitmeasure, windowEditUnitmeasure;
	private Textbox tbCerca;
	private Listbox boxUnitmeasure;

	private List tutte_le_unitmeasure;
	private boolean lNuovo;
	private Toolbarbutton buttonSeleziona;

	private ListModelList listModelList;
	private Integer idSelezionato = 0;

	protected Map<String, Object> args;
	private Object unitmeasureItem;
	private Unitmeasure modUnitmeasure;
	// edit
	private Intbox id;
	private Textbox um, descum;

	public void onCreate$windowUnitmeasure(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		String tastoSeleziona = (String) args.get("tastoSeleziona");
		tastoSeleziona = (tastoSeleziona == null || tastoSeleziona.isEmpty() ? "N"
				: tastoSeleziona);
		boolean lTastoSeleziona = tastoSeleziona.equals("S");
		if (!lTastoSeleziona) {
			buttonSeleziona.setVisible(false);
		}
		idSelezionato = (Integer) args.get("idselezionato");

		listModelList = new ListModelList();
		tutte_le_unitmeasure = new UnitmeasureController().getUnitmeasureList(null);
		listModelList.addAll(tutte_le_unitmeasure);
		boxUnitmeasure.setModel(listModelList);
		boxUnitmeasure.setItemRenderer(new UnitmeasureItemRenderer());
		
		if (idSelezionato!=null && idSelezionato!=0){
			for (int i = 0; i < tutte_le_unitmeasure.size(); i++) {
				Unitmeasure unitmeasure = (Unitmeasure)tutte_le_unitmeasure.get(i);
				if (unitmeasure.getId()==idSelezionato.intValue()){
					boxUnitmeasure.setSelectedIndex(i);
					break;
				}
			}
		}

	}

	public void afterCompose() {

		// wire variables
		ConventionWires.wireVariables(this, this);

		// auto forward
		ConventionWires.addForwards(this, this);

	}

	public void onOK$tbCerca(Event event){
		cerca();
	}
	
	public void onClick$buttonCerca(Event event) {
		cerca();
	}
	
	
	private void cerca(){
		listModelList = new ListModelList();
		tutte_le_unitmeasure = new UnitmeasureController().getUnitmeasureList(tbCerca
				.getValue());
		listModelList.addAll(tutte_le_unitmeasure);
		boxUnitmeasure.setModel(listModelList);
		boxUnitmeasure.setItemRenderer(new UnitmeasureItemRenderer());		
	}
	
	
	
	public void onDoubleClicked(Event event) {
		if (buttonSeleziona.isVisible()) {
			seleziona();
		} else {
			modifica(false);
		}
	}
	
	
	public void onClick$buttonSeleziona(Event event) {

		seleziona();

	}

	public void seleziona() {
		if (boxUnitmeasure.getSelectedIndex() >= 0 && buttonSeleziona.isVisible()) {
			Object oUnitmeasure = boxUnitmeasure.getSelectedItem().getAttribute(
					"rigaUnitmeasure");
			String codiceSelezionato = ""+((Unitmeasure) oUnitmeasure).getId();
			Sessions.getCurrent().setAttribute("codiceUnitmeasureSelezionato",
					codiceSelezionato);
			windowUnitmeasure.detach();
		}
	}


	@Override
	public void onClick$buttonNuovo(Event event) {
		modifica(true);
	}

	@Override
	public void onClick$buttonModifica(Event event) {
		modifica(false);
	}
	
	private void modifica(boolean nuovo){
		try {

			int nIndex = boxUnitmeasure.getSelectedIndex();

			if (!nuovo && nIndex == -1) { // nessuna riga selezionata

				Messagebox.show("Select a Unit measure to modify", "Information", Messagebox.OK, Messagebox.INFORMATION);

			} else {
				HashMap map = new HashMap();
				if (nuovo){
					map.put("lNuovo", true);
				}
				map.put("boxUnitmeasure", boxUnitmeasure);
				Window finestraEditUnitmeasure = (Window) Executions.createComponents(
						"/editUnitmeasure.zul", null, map);
				finestraEditUnitmeasure.doModal();
			}

		} catch (SuspendNotAllowedException e) {
			e.printStackTrace();
		}
	}
	
	
	
	@Override
	public void onClick$buttonCancella(Event event) {
		// TODO Auto-generated method stub
		
	}	

	public class UnitmeasureItemRenderer implements ListitemRenderer {

		public void render(Listitem li, Object data, int index) {
			new Listcell(""+((Unitmeasure) data).getId()).setParent(li);
			new Listcell(((Unitmeasure) data).getUm()).setParent(li);
			new Listcell(((Unitmeasure) data).getDescum()).setParent(li);
			li.setAttribute("rigaUnitmeasure", data);
			ComponentsCtrl.applyForward(li, "onDoubleClick=onDoubleClicked");
		}
	}

	
	
	// EDIT UNIT MEASURE: NEW/MODIFY
	public void onCreate$windowEditUnitmeasure(Event event) {

		CreateEvent ce = (CreateEvent) ((ForwardEvent) event).getOrigin();
		args = (Map<String, Object>) ce.getArg();
		
		boxUnitmeasure = (Listbox) args.get("boxUnitmeasure");

		if (args.containsKey("lNuovo")) {
			lNuovo = true;
		} else {
			lNuovo = false;
		}

		if (!lNuovo) {
			unitmeasureItem = boxUnitmeasure.getSelectedItem().getAttribute("rigaUnitmeasure");
			modUnitmeasure = new UnitmeasureController().refreshUnitmeasure((Unitmeasure) unitmeasureItem);
			unitmeasureItem = modUnitmeasure;
			windowEditUnitmeasure.setTitle("Edit Unit Measure");
			um.setFocus(true);
			id.setValue(modUnitmeasure.getId());
			um.setValue(modUnitmeasure.getUm());
			descum.setValue(modUnitmeasure.getDescum());
		} else {
			windowEditUnitmeasure.setTitle("New Unit Measure");
			um.setFocus(true);
		}
	}
	
	public void onClick$btnAnnulla(Event event){
		windowEditUnitmeasure.detach();
	}
	
	public void onClick$btnConferma(Event event){
		if (lNuovo){
			modUnitmeasure = new Unitmeasure();
		} else {

		}
		String testoMsg = "";
		
		modUnitmeasure.setId(id.getValue());
		modUnitmeasure.setUm(General.toUpperAncheNull(um.getValue()));
		modUnitmeasure.setDescum(General.toUpperAncheNull( (descum.getValue()!=null?descum.getValue():"")));
		
		if (lNuovo){
			new UnitmeasureController().addUnitmeasure(modUnitmeasure);
			testoMsg = "Adding Unit Measure: "+ General.trimNull( modUnitmeasure.getDescum() );
		} else {
			new UnitmeasureController().updateUnitmeasure(modUnitmeasure);
			testoMsg = "Updating Unit Measure: "+ General.trimNull( modUnitmeasure.getDescum() );			
		}
		
		General.showNotify( testoMsg, windowEditUnitmeasure);
		
		windowEditUnitmeasure.detach();
		
		// aggiorna listbox
		
		if (lNuovo){
			ListModelList lml = (ListModelList) boxUnitmeasure.getListModel();
			lml.add(modUnitmeasure);
			boxUnitmeasure.setSelectedIndex(lml.indexOf(modUnitmeasure));
		} else {
			ListModelList lml = (ListModelList) boxUnitmeasure.getListModel();
			Object oUnitmeasureItem = boxUnitmeasure.getSelectedItem().getAttribute("rigaUnitmeasure");
			if (lml.indexOf(oUnitmeasureItem) == -1) {
				// non trovato... quindi non lo aggiorno
			} else {
				lml.set(lml.indexOf(oUnitmeasureItem), modUnitmeasure);
			}
		}		
	}
	
	
}
